package org.msi.bayesiannetwork;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>This is utility class which defines common methods used in couple of placses in this componenet.</p>
 *
 * @author Jakub Narloch
 * @version 1.0
 */
public class Utils {

    /**
     * <p>Converts the int value into list of probabilities.</p>
     *
     * @param index         the int value to convert
     * @param variableCount the number of variables
     *
     * @return list of boolean sequences
     */
    public static List<Boolean> intToBooleanList(int index, int variableCount) {

        List<Boolean> result = new ArrayList<Boolean>();
        for (int i = variableCount - 1; i >= 0; i--) {

            result.add((index & (1 << i)) > 0);
        }

        return result;
    }

    /**
     * <p>Returns list containing names of the variables for the passed list with names of the nodes.</p>
     *
     * @param nodeNames         the names of the nodes
     * @param nodeToVariableMap the map containing for each entry node and variable name pair
     *
     * @return the list containing the name of the variables for the given node names list
     *
     * @throws NodeNotFoundException if the node with given name does not exists
     */
    public static List<String> getVariableNamesFromNodes(List<String> nodeNames, Map<String, String> nodeToVariableMap) throws NodeNotFoundException {

        List<String> variableNames = new ArrayList<String>();

        for (String nodeName : nodeNames) {
            if (!nodeToVariableMap.containsKey(nodeName)) {
                throw new NodeNotFoundException(String.format("Node with name %s does not exists.", nodeName));
            }

            variableNames.add(nodeToVariableMap.get(nodeName));
        }

        return variableNames;
    }
}
